# weather.py
from fastmcp import FastMCP
import sys
import logging
import os
import requests
from typing import Dict, Any

logger = logging.getLogger('Weather')

# Create an MCP server
mcp = FastMCP("Weather")

# 高德天气API配置
AMAP_WEATHER_API_KEY = os.getenv("AMAP_WEATHER_API_KEY", "efbbb0c9f57c6bed9ccc737b5dc2d259")
AMAP_WEATHER_API_URL = "https://restapi.amap.com/v3/weather/weatherInfo"

@mcp.tool()
def get_weather(city: str) -> Dict[str, Any]:
    """获取指定城市的天气信息。需要提供城市名称，例如：北京、上海等。"""
    if not AMAP_WEATHER_API_KEY:
        return {"success": False, "error": "未配置高德天气API密钥，请设置环境变量AMAP_WEATHER_API_KEY"}
    
    try:
        # 调用高德天气API
        params = {
            "key": AMAP_WEATHER_API_KEY,
            "city": city,
            "extensions": "base",  # 获取实时天气
            "output": "JSON"
        }
        
        response = requests.get(AMAP_WEATHER_API_URL, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        
        # 检查API返回状态
        if data.get("status") != "1":
            return {"success": False, "error": f"API调用失败: {data.get('info', '未知错误')}"}
        
        # 解析天气数据
        weather_info = data.get("lives", [])
        if not weather_info:
            return {"success": False, "error": "未找到该城市的天气信息"}
        
        live_weather = weather_info[0]
        result = {
            "success": True,
            "city": live_weather.get("city"),
            "temperature": live_weather.get("temperature"),
            "humidity": live_weather.get("humidity"),
            "weather": live_weather.get("weather"),
            "wind_direction": live_weather.get("winddirection"),
            "wind_power": live_weather.get("windpower"),
            "report_time": live_weather.get("reporttime")
        }
        
        logger.info(f"获取{city}天气信息成功")
        return result
        
    except requests.RequestException as e:
        logger.error(f"请求天气API时发生网络错误: {e}")
        return {"success": False, "error": f"网络请求错误: {str(e)}"}
    except Exception as e:
        logger.error(f"获取天气信息时发生错误: {e}")
        return {"success": False, "error": f"获取天气信息失败: {str(e)}"}

# Start the server
if __name__ == "__main__":
    mcp.run(transport="stdio")